 package com.onlineMIS.action.headQ.inventoryFlow;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.onlineMIS.ORM.DAO.Response;
import com.onlineMIS.ORM.DAO.chainS.ChainUtility;
import com.onlineMIS.ORM.DAO.chainS.inventoryFlow.ChainInventoryFlowOrderService;
import com.onlineMIS.ORM.DAO.chainS.user.ChainStoreService;
import com.onlineMIS.ORM.DAO.headQ.inventory.HeadqInventoryService;
import com.onlineMIS.ORM.entity.base.BaseOrder;
import com.onlineMIS.ORM.entity.chainS.inventoryFlow.ChainInvenTraceInfoVO;
import com.onlineMIS.ORM.entity.chainS.inventoryFlow.ChainInventoryFlowOrder;
import com.onlineMIS.ORM.entity.chainS.inventoryFlow.ChainInventoryFlowOrderProduct;
import com.onlineMIS.ORM.entity.chainS.sales.ChainStoreSalesOrder;
import com.onlineMIS.ORM.entity.chainS.user.ChainStore;
import com.onlineMIS.ORM.entity.chainS.user.ChainUserInfor;
import com.onlineMIS.ORM.entity.chainS.vip.ChainVIPCard;
import com.onlineMIS.ORM.entity.headQ.inventory.HeadqInvenTraceInfoVO;
import com.onlineMIS.ORM.entity.headQ.inventory.HeadqInventoryFlowOrder;
import com.onlineMIS.ORM.entity.headQ.inventory.HeadQInventoryStore;
import com.onlineMIS.ORM.entity.headQ.user.UserInfor;
import com.onlineMIS.action.BaseAction;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.loggerLocal;
import com.onlineMIS.converter.JSONUtilDateConverter;
import com.onlineMIS.filter.SystemParm;
import com.onlineMIS.sorter.ChainInveProductSort;
import com.opensymphony.xwork2.ActionContext;

/**
 * action to 
 * @author fredo
 *
 */
@SuppressWarnings("serial")
public class HeadqInventoryFlowJSPAction extends HeadqInventoryFlowAction{
	private final String CHAIN_INVENTORY_REPORT_TEMPLATENAME = "ChainInventoryReportTemplate.xls";
	private final String CHAIN_INVENTORY_REPORT_NAME = "KuCunBiao.xls";
	
	
	@Autowired
	private HeadqInventoryService flowService;
	
	
	/**
	 * 用户准备创建单据
	 * @return
	 */
	public String preCreateInventoryFlowOrder(){
		loggerLocal.info("HeadqInventoryFlowJSPAction - preCreateInventoryFlowOrder");
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		
		HeadqInventoryFlowOrder order = new HeadqInventoryFlowOrder();
		
		//prepare the 
		ChainUtility.calculateParam(formBean, order);
		
		headqInventoryService.prepareCreateOrderUI(formBean,uiBean, loginUserInfor);
		
		return "flowOrder";
	}
	
	public String preInventoryRpt(){
		
		return "preInventoryRpt";
	}
	
	/**
	 * 下载库存报表
	 * @return
	 */
	public String downloadHeadqInventory(){
		loggerLocal.info("HeadqInventoryFlowJSPAction - downloadHeadqInventory");
		HttpServletRequest request = (HttpServletRequest)ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);   
		String contextPath= request.getRealPath("/"); 

		Response response = new Response();
		try {
			response = headqInventoryService.generateInventoryExcelReport(formBean.getStoreId(), formBean.getYearId(), formBean.getQuarterId(), formBean.getBrandId(), contextPath + "WEB-INF\\template\\" + CHAIN_INVENTORY_REPORT_TEMPLATENAME);     
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}
 
		if (response.getReturnCode() == Response.SUCCESS){
		    InputStream excelStream= (InputStream)response.getReturnValue();
		    formBean.setFileStream(excelStream);
		    formBean.setFileName(CHAIN_INVENTORY_REPORT_NAME);
		    return "download"; 
		} else 
			return ERROR;
	}
	
	/**
	 * 打开库存跟踪
	 * @return
	 */
	public String openInvenTracePage(){
		loggerLocal.info("HeadqInventoryFlowJSPAction - openInvenTracePage");
		Response response = headqInventoryService.getInventoryTraceInfor(formBean.getStoreId(), formBean.getPbId());
		if (response.getReturnCode() == Response.SUCCESS){
			Map<String, List> data = (Map<String, List>)response.getReturnValue();
			List<HeadqInvenTraceInfoVO> traceVOs = data.get("rows");
			List<HeadqInvenTraceInfoVO> footers = data.get("footer");
			
			if (footers != null && footers.size() >0)
				uiBean.setTraceFooter(footers.get(0));
			
			uiBean.setTraceItems(traceVOs);
		}
		return "OpenCheckInventoryTracePage";
	}
	
	
	
	
	/**
	 * to save the 报损单，报溢单，调货单 to final order
	 * 
	 * @return
	 */
	public String saveToFinal() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + this.getClass().getName() + "." + "saveToFinal ");

		try {
			
			flowService.saveToFinal(formBean.getFlowOrder(), loginUser);

			addActionMessage("已经成功保存单据");
		} catch (Exception e) {
			loggerLocal.error("ChainInventoryFlowAction.saveToFinal: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			addActionError("保存单据发生系统错误，请联系系统管理员");
		}

		return postSubmitFlowOrder(true,formBean);
	}
	
	
	private String postSubmitFlowOrder(boolean toFinalize,HeadqInventoryFlowFormBean formBean) {
		// clear the data
		int orderType = formBean.getFlowOrder().getType();

		

		if (orderType == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {
			formBean.getFlowOrder().setType(HeadqInventoryFlowOrder.OVER_FLOW_ORDER);
			return preCreateOverflowOrder(formBean);
		} else if (orderType == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {
			formBean.getFlowOrder().setType(HeadqInventoryFlowOrder.FLOW_LOSS_ORDER);
			return preCreateOverflowOrder(formBean);
		} else if (orderType == HeadqInventoryFlowOrder.INVENTORY_ORDER)
			return preCreateInventoryOrder();
		else if (orderType == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER)
			return preCreateInventoryTransferOrder();
		else
			return ERROR;
	}
	
	/**
	 * go to 报溢单 (overflow order) 报溢单
	 */
	public String preCreateOverflowOrder(HeadqInventoryFlowFormBean formBean) {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + this.getClass().getName() + "." + "preCreateOverflowOrder");

		flowService.prepareCreateOrderUI(formBean, uiBean, loginUser);

		ChainUtility.calculateParam(formBean, formBean.getFlowOrder());

		return "editFlowOrder";
	}
	
	
	/**
	 * go to create 库存单 (inventory order)
	 * 
	 * @return
	 */
	public String preCreateInventoryOrder() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + this.getClass().getName() + "." + "preCreateOverflowOrder");

		HeadqInventoryFlowOrder order = formBean.getFlowOrder();

		flowService.prepareCreateFlowOrderFormUIBean(loginUser, uiBean, formBean, order);

		// set the order type
		formBean.getFlowOrder().setType(HeadqInventoryFlowOrder.INVENTORY_ORDER);

		return "editInventoryOrder";
	}
	
	
	
	/**
	 * go to create 调货单 (inventory transfer order) 总部仓库调货暂时不管
	 * 
	 * @return
	 */
	public String preCreateInventoryTransferOrder() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + this.getClass().getName() + "." + "preCreateOverflowOrder");

		HeadqInventoryFlowOrder order = formBean.getFlowOrder();

		ChainUtility.calculateParam(formBean, order);

		formBean.getFlowOrder().setType(HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER);

		flowService.prepareCreateFlowOrderFormUIBean(loginUser, uiBean, formBean, order);

		return "editInventoryTransferOrder";
	}
	
	
	/**
	 * 搜索库存类单据
	 * 
	 * @return
	 */
	public String selectInventoryFlowOrder() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - preCreateInventoryFlowOrder");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		headqInventoryService.prepareSearchFlowOrderUI(formBean, uiBean, loginUserInfor);

		return "searchOrder";
	}
	
	
	/**
	 * 获取当前库存前，需要提前选择总部仓库
	 * 
	 * @return
	 */
	public String preGetCurrentInventory() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - preGetCurrentInventory");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		Response response = new Response();

		try {
			response = headqInventoryService.getHeadqInventoryStore();

		} catch (Exception e) {
			loggerLocal.error(e);
			response.setQuickValue(Response.ERROR, response.getMessage());
		}
		List<HeadQInventoryStore> headStores = (List<HeadQInventoryStore>) response.getReturnValue();
		uiBean.setStores(headStores);

		return "inventoryStatistics";

	}
	
	
	
	/**
	 * 获取当前仓库的库存
	 * 
	 * @return
	 */
	public String getLevelOneCurrentInventory() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - getLevelOneCurrentInventory");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		int storeId = formBean.getStoreId();

		headqInventoryService.prepareGetStoreInventoryRpt(formBean, uiBean);

		return "preInventoryRpt";
	}
	
	
	/**
	 * to load the inventory flow order
	 * 
	 * @return
	 */
	public String loadOrder() {
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		int orderId = formBean.getFlowOrder().getId();

		HeadqInventoryFlowOrder order = flowService.getOrderById(orderId, loginUserInfor);

		ChainUtility.calculateParam(formBean, order);

		int orderStatus = order.getStatus();
		int orderType = order.getType();
		if (orderStatus == HeadqInventoryFlowOrder.STATUS_COMPLETE
				|| orderStatus == HeadqInventoryFlowOrder.STATUS_CANCEL) {
			flowService.prepareDisplayFlowOrderFormUIBean(loginUserInfor, uiBean, formBean, order);
			if (orderType == HeadqInventoryFlowOrder.INVENTORY_ORDER) {
				// 1. sort the flow order by year, quarter, brand, product code
//    		   Collections.sort(order.getProductList(), new HeadqInventoryFlowOrderProduct());

				return "displayInventoryReport";
			} else if (orderType == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER)
				return "displayInventoryTransferOrder";
			else
				return "displayFlowOrder";
		} else if (orderStatus == HeadqInventoryFlowOrder.STATUS_DRAFT) {

			if (orderType == HeadqInventoryFlowOrder.INVENTORY_ORDER) {
				flowService.prepareCreateFlowOrderFormUIBean(loginUserInfor, uiBean, formBean, order);

				return "editInventoryOrder";
			} else if (orderType == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {
				flowService.prepareCreateInvenTransferOrderFormUIBean(loginUserInfor, uiBean, formBean, order);
				return "editInventoryTransferOrder";
			} else {
				flowService.prepareCreateFlowOrderFormUIBean(loginUserInfor, uiBean, formBean, order);
				return "editFlowOrder";
			}
		} else {
			addActionError("你没有访问这个单据的权限");
			return ERROR;
		}

	}
	
	
	/**
	 * to save the inventory order to draft 库存盘点单
	 * 
	 * @return
	 */
	public String saveInventoryToDraft() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + this.getClass().getName() + "." + "saveToFinal ");

		Response response = new Response();
		try {
			response = flowService.saveInventoryToDraft(formBean.getFlowOrder(), formBean.getInventory(), loginUser);
		} catch (Exception e) {
			loggerLocal.error("HeadqInventoryFlowAction.saveInventoryToDraft: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			addActionError("保存单据发生系统错误，请联系系统管理员");
		}

		if (response.getReturnCode() != Response.SUCCESS) {
			addActionError(response.getMessage());
			return postSubmitFlowOrder(false,formBean);
		} else {
			addActionMessage(response.getMessage());
			int orerId = (Integer) response.getReturnValue();
			formBean.getFlowOrder().setId(orerId);
			return loadOrder();
		}
	}
	
	

	/**
	 * 一键修复库存，只会核对单据上的物品的库存
	 * 
	 * @return
	 */
	public String oneKeyAdjustInventory() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + this.getClass().getName() + "." + "saveToFinal ");

		Response response = new Response();
		try {
			response = flowService.adjustInventory(formBean.getFlowOrder(), loginUser);
		} catch (Exception e) {
			e.printStackTrace();
			loggerLocal.error("HeadqInventoryFlowAction.saveToDraft: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			addActionError("保存单据发生系统错误，请联系系统管理员");
		}

		if (response.getReturnCode() != Response.SUCCESS) {
			addActionError(response.getMessage());
			flowService.prepareCreateFlowOrderFormUIBean(loginUser, uiBean, formBean, formBean.getFlowOrder());
			return "editInventoryOrder";
		} else {
			String message = response.getMessage();
			response = flowService.calculateInventoryOrder(formBean.getFlowOrder());

			if (response.getReturnCode() != Response.SUCCESS) {
				addActionError(response.getMessage());
			} else {
				addActionMessage(message);
				HeadqInventoryFlowOrder flowOrder = (HeadqInventoryFlowOrder) response.getReturnValue();
				flowService.prepareCreateFlowOrderFormUIBean(loginUser, uiBean, formBean, flowOrder);
			}
			return "editInventoryOrder";
		}
	}
	
	

	/**
	 * 此单据应该是连锁店的实际库存,此功能将使用此单据完全取代电脑库存 扎账
	 * 
	 * @return
	 */
	public String oneKeyClearAndAdjustInventory() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + this.getClass().getName() + "." + "saveToFinal ");

		Response response = new Response();
		try {
			response = flowService.clearAndadjustInventory(formBean.getFlowOrder(), loginUser);
		} catch (Exception e) {
			loggerLocal.error("HeadqInventoryFlowAction.saveToDraft: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			addActionError("保存单据发生系统错误，请联系系统管理员");
		}

		if (response.getReturnCode() != Response.SUCCESS) {
			addActionError(response.getMessage());
			flowService.prepareCreateFlowOrderFormUIBean(loginUser, uiBean, formBean, formBean.getFlowOrder());
			return "editInventoryOrder";
		} else {
			String message = response.getMessage();
			response = flowService.calculateInventoryOrder(formBean.getFlowOrder());

			if (response.getReturnCode() != Response.SUCCESS) {
				addActionError(response.getMessage());
			} else {
				addActionMessage(message);
				HeadqInventoryFlowOrder flowOrder = (HeadqInventoryFlowOrder) response.getReturnValue();
				flowService.prepareCreateFlowOrderFormUIBean(loginUser, uiBean, formBean, flowOrder);
			}
			return "editInventoryOrder";
		}
	}
	
	/**
	 * 生成最终报表 action to generate the inventory report
	 * 
	 * @return
	 */
	public String genInventoryReport() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + this.getClass().getName() + "." + "saveToFinal ");

		Response response = new Response();
		try {
			response = flowService.genInventoryReport(formBean.getFlowOrder(), formBean.getInventory(), loginUser);
		} catch (Exception e) {
			loggerLocal.error("ChainInventoryFlowAction.saveToDraft: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			addActionError("保存单据发生系统错误，请联系系统管理员");
		}

		if (response.getReturnCode() != Response.SUCCESS) {
			addActionError(response.getMessage());
			return postSubmitFlowOrder(false,formBean);
		} else {
			addActionMessage(response.getMessage());
			int orerId = (Integer) response.getReturnValue();
			formBean.getFlowOrder().setId(orerId);
			return loadOrder();
		}
	}
	
	
	/**
	 * 下载条码 action to download the barcodes
	 * 
	 * @return
	 */
	public String getBarcodeFile() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + this.getClass().getName() + "." + "saveToFinal ");
		InputStream fileStream = null;
		Date date = new Date();
		formBean.setFileName("barcode.txt");

		File barcodeFile = new File(SystemParm.getParm("BARCODE_DOWNLOAD_PATH"));
		if (!barcodeFile.exists())
			fileStream = flowService.genBarcodeFile();
		else {
			try {
				fileStream = new FileInputStream(barcodeFile);
			} catch (FileNotFoundException e) {
				loggerLocal.error(e);
				fileStream = flowService.genBarcodeFile();
			}
		}

		formBean.setFileStream(fileStream);

		return "download";
	}
	
	/**
	 * to save the 报损单，报溢单，调货单 to draft
	 * 
	 * @return
	 */
	public String saveToDraft() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + this.getClass().getName() + "." + "saveToDraft ");

		try {
			flowService.saveToDraft(formBean.getFlowOrder(),formBean.getInventory(), loginUser);

			addActionMessage("已经成功保存单据到草稿");
		} catch (Exception e) {
			loggerLocal.error("ChainInventoryFlowAction.saveToDraft: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			addActionError("保存单据发生系统错误，请联系系统管理员");
		}

		return postSubmitFlowOrder(true,formBean);
	}
	
	
	/**
	 * delete the inventory flow order
	 * 
	 * @return
	 */
	public String deleteOrder() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - deleteOrder");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		int orderId = formBean.getFlowOrder().getId();
		flowService.deleteOrderById(orderId, loginUserInfor);
		addActionMessage("已经成功删除单据");
		
		return preSearchInvenFlowOrder();
	}
	
	public String preSearchInvenFlowOrder() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - preSearchInvenFlowOrder");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		headqInventoryService.prepareSearchFlowOrderUI(formBean, uiBean, loginUserInfor);

		return "searchOrder";
	}
	
	/**
	 * 下载库存类单据明细
	 * 
	 * @return
	 */
	public String downloadFlowOrder() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - preCreateInventoryFlowOrder");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		Response response = new Response();
		try {
			response = flowService.downloadFlowOrder(formBean.getFlowOrder().getId(), loginUserInfor);
		} catch (Exception e) {
			e.printStackTrace();
			addActionError(e.getMessage());
			return "error";
		}

		List<Object> values = (List<Object>) response.getReturnValue();

		formBean.setFileStream((InputStream) values.get(0));
		formBean.setFileName("zongbukucun--" + formBean.getFlowOrder().getId() + ".xls");
//		System.out.println(values.get(1).toString());

		return "download";
	}
	
	
	/**
	 * to cancel the order 红冲单据
	 * 
	 * @return
	 */
	public String cancelOrder() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - deleteOrder");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		int orderId = formBean.getFlowOrder().getId();

		Response response = flowService.cancelOrder(orderId, loginUserInfor);
		if (response.getReturnCode() == Response.SUCCESS) {
			addActionMessage(response.getMessage());
			return preSearchInvenFlowOrder();
		} else {
			addActionError(response.getMessage());
			return loadOrder();
		}
	}
	
}
